package logic

import (
	"context"
	"taobao_svc/models/mysql"

	"taobao_svc/internal/svc"
	"taobao_svc/taobao"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductListLogic {
	return &ProductListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 商品列表
func (l *ProductListLogic) ProductList(in *taobao.ProductListRequest) (*taobao.ProductListResponse, error) {
	// todo: add your logic here and delete this line

	page := in.Page
	if page <= 0 {
		page = 1
	}
	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}
	offset := (page - 1) * pageSize
	var product []mysql.Product
	mysql.DB.Debug().Offset(int(offset)).Limit(int(pageSize)).Find(&product)
	var productList []*taobao.ProductList
	for _, m := range product {
		list := taobao.ProductList{
			Name:        m.Name,
			CategoryId:  int64(m.CategoryID),
			Description: m.Description,
			Price:       float32(m.Price),
			Stock:       int64(m.Stock),
			Status:      int64(m.Status),
		}
		productList = append(productList, &list)
	}
	return &taobao.ProductListResponse{
		List: productList,
	}, nil
}
